import {resolve} from 'node:path'
import {defineConfig} from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import ViteComponents from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import AutoExport from './src/plugins/autoExport';
import GlobalComponent from './src/plugins/globalComponent'
import getRemoteIp from './src/plugins/getRemoteIp'
import env from './src/qly/env'

// https://vitejs.dev/config/
export default defineConfig(configEnv => {
    const config = {
        define: {
            __DEV_MODE__: JSON.stringify(configEnv.mode),
            __DEV_REMOTE_IP__: JSON.stringify(getRemoteIp()),
        },
        resolve: {
            alias: {
                '@': resolve(__dirname, 'src'),
            },
        },
        plugins: [
            AutoExport({
                watchDir: 'src/apis',
                outputFile: 'index.js',
            }),
            GlobalComponent(),
            // https://github.com/antfu/unplugin-vue-components
            ViteComponents({
                dts: true,
                globs: ['src/components/*/index.vue','src/projects/*/index.vue']
            }),
            uni(),
            // https://github.com/antfu/unplugin-auto-import
            AutoImport({
                dts: true,
                imports: [
                    'vue',
                    'uni-app',
                    {
                        '@/qly/index': ['qly'],
                    }
                ],
            }),
        ],
    }
    
    if (env.viteEnv && configEnv.command === 'serve') {
        const viteEnv = env.viteEnv[configEnv.mode]
        config.server = {
            proxy: {
                '/api': {
                    changeOrigin: true,
                    target: new URL(viteEnv.baseUrl).origin,
                    // rewrite: path => path.replace(/^\/proxy/, ''),
                    ws: true,
                }
            }
        }
    }
    
    return config
})
